import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets,losses,layers,metrics,Sequential,optimizers
from resnet_train import resnet18

def preprocess(x, y):
    x = 2 * tf.cast(x, dtype=tf.float32) / 255. - 1
    y = tf.cast(y, dtype=tf.int32)

    return x,y

(x, y), (x_test, y_test) = datasets.cifar100.load_data()
#降维
y = tf.squeeze(y)
y_test = tf.squeeze(y_test)
print(x.shape, y.shape, x_test.shape, y_test.shape)

batchsz = 128

train_db = tf.data.Dataset.from_tensor_slices((x, y))
test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))
train_db = train_db.map(preprocess).shuffle(10000).batch(batchsz)
test_db = test_db.map(preprocess).shuffle(10000).batch(batchsz)

sample = next(iter(train_db))
print(sample[0].shape, sample[1].shape)

def main():

    model = resnet18()
    model.build(input_shape=(None, 32, 32, 3))
    optimizer = optimizers.Adam(lr=1e-3)

    for epoch in range(100):

        for step, (x, y) in enumerate(train_db):

            with tf.GradientTape() as tape:

                #[b, 100]
                logits = model(x)
                y_onehot = tf.one_hot(y, depth=100)
                loss = tf.reduce_mean(tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True))

            grads = tape.gradient(loss, model.trainable_variables)
            optimizer.apply_gradients(zip(grads, model.trainable_variables))

            if step % 50 == 0:
                print(epoch, step, 'loss:', float(loss))

        total_num = 0
        total_correct = 0
        for x, y in test_db:

            logits = model(x)
            prob = tf.nn.softmax(logits, axis=1)
            pred = tf.argmax(prob, axis=1)
            pred = tf.cast(pred, dtype=tf.int32)
            result = tf.cast(tf.equal(pred, y), dtype=tf.int32)
            result = tf.reduce_sum(result)

            total_correct += int(result)
            total_num += x.shape[0]
        print(epoch, 'accuracy:', total_correct / total_num)

    model.save_weights('resnet18/resnet18_weights.ckpt')


if __name__ == '__main__':
    main()